package com.op.parcel.boot.logger;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.op.parcel.common.api.R;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * 请求日志
 *
 * @author xuan🐽
 */
@Slf4j
@Aspect
@Component
public class RequestLogAspect {

	@Autowired
	private ObjectMapper objectMapper;

	@Around(
		"execution(!static com.op.parcel.common.api.R<*> *(..)) && " +
			"(@within(org.springframework.stereotype.Controller) || " +
			"@within(org.springframework.web.bind.annotation.RestController))"
	)
	public Object aroundApi(ProceedingJoinPoint pjp) throws Throwable {
		long startTime = System.currentTimeMillis();

		ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
		HttpServletRequest request = attributes.getRequest();

		R result = null;

		log.info("请求地址 : {}", request.getRequestURL().toString());
		log.info("请求方式 : {}", request.getMethod());
		log.info("请求ip : {}", request.getRemoteAddr());
		log.info("方法 : {}", pjp.getSignature().getDeclaringTypeName() + "." + pjp.getSignature().getName());
		Object[] args = pjp.getArgs();
		for (Object arg : args) {
			if (arg instanceof HttpServletRequest) {
				continue;
			}
			log.info("参数 : {}", objectMapper.writeValueAsString(arg));
		}

		try {
			result = (R) pjp.proceed();
			log.info(pjp.getSignature() + "use time:" + (System.currentTimeMillis() - startTime));
		} finally {
			/*if (result != null && result.isSuccess()) {
				log.info("返回内容 : " + objectMapper.writeValueAsString(result.getData()));
			}*/
		}

		return result;
	}

}
